package com.eight.cloud.core.utils.format;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.eight.cloud.core.global.exception.CustomException;

import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 数据格式校验
 *
 * @ClassName: Validate
 * @Author: TXC
 * @Date: 2024-09-19 15:08
 **/
public class Validate {
    private static final Pattern ID_CARD_PATTERN = Pattern.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|12]\\d)|3[0-1])\\d{3}([0-9]|[Xx])$");
    private static final Integer[] WEIGHT_FACTORS = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    private static final String[] CHECK_DIGITS = {"1", "0", "10", "9", "8", "7", "6", "5", "4", "3", "2"};
    private static final Pattern MOBILE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");

    public static boolean isIdCard(String idCard) {
        if (ObjectUtil.isEmpty(idCard) || idCard.length() != 18) {
            return false;
        }
        Matcher matcher = ID_CARD_PATTERN.matcher(idCard);
        if (!matcher.matches()) {
            return false;
        }
        try {
            int sum = 0;
            for (int i = 0; i < 17; i++) {
                int digit = Character.getNumericValue(idCard.charAt(i));
                int weight = WEIGHT_FACTORS[i];
                sum += digit * weight;
            }
            int mod = sum % 11;
            String lastDigit = idCard.substring(17, 18);
            if (mod == 2) {
                return "x".equalsIgnoreCase(lastDigit);
            } else {
                return CHECK_DIGITS[mod].equals(lastDigit);
            }
        } catch (NumberFormatException | IndexOutOfBoundsException e) {
            // 记录日志或提供更详细的错误信息
            System.err.println("Error validating ID card: " + e.getMessage());
            return false;
        }
    }

    public static boolean isMobile(String src) {
        if(StrUtil.isEmpty(src)) {
            return false;
        }
        Matcher m = MOBILE_PATTERN.matcher(src);
        return m.matches();
    }

    public static void checkField(Predicate<Object> predicate, Object value, String fieldName) {
        if (predicate.test(value)) {
            throw new CustomException(500, fieldName + "不能为空");
        }
    }
}

